<!DOCTYPE html>

<html lang="en">
  <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>安全（Security） &mdash; Phalcon 2.0.0 文档</title>
    <meta name="keywords" content="php, phalcon, phalcon php, php framework, faster php framework"><link rel="stylesheet" type="text/css" href="../_static/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="http://static.phalconphp.com/css/phalcon.min.css" />
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:700,400' rel='stylesheet' type='text/css'>
    <link href="http://fonts.googleapis.com/css?family=Merriweather:400,700" rel="stylesheet" type="text/css" />
    <!--
    EUROPE <link href='https://fonts.googleapis.com/css?family=Open+Sans:700,400&subset=latin-ext' rel='stylesheet' type='text/css'>
    GREEK <link href='https://fonts.googleapis.com/css?family=Open+Sans:700,400&subset=greek-ext' rel='stylesheet' type='text/css'>
    RUSSIA <link href='https://fonts.googleapis.com/css?family=Open+Sans:700,400&subset=cyrillic-ext,latin' rel='stylesheet' type='text/css'>
    -->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/docs.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.0.0',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>

    <script src="../_static/jquery.min.js"></script>
    <script type="text/javascript" src="../_static/docs.js"></script>
    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="top" title="Phalcon 2.0.0 文档" href="../index.html" />
    <link rel="next" title="加密与解密（Encryption/Decryption）" href="crypt.html" />
    <link rel="prev" title="使用缓存提高性能（Improving Performance with Cache）" href="cache.html" /> 
  </head>
  <body>

<header class="page-header">
    <nav class="navbar" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-menu-container">
                    <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
                </button>
                <a class="navbar-brand phalcon-logo" href="/"><span itemprop="name" class="sr-only">Phalcon PHP</span></a>
            </div>

            <div class="collapse navbar-collapse navbar-right" id="main-menu-container">
                <ul class="nav navbar-nav main-menu">
                  <li class="first"><a href="http://phalconphp.com/en/download" class="header-nav-link">Download</a></li>
                  <li><a href="http://docs.phalconphp.com/en/latest/index.html" class="header-nav-link" target="_blank">Documentation</a></li>
                  <li><a href="http://forum.phalconphp.com/" class="header-nav-link" target="_blank">Forum</a></li>
                  <li><a href="http://blog.phalconphp.com/" class="header-nav-link" target="_blank">Blog</a></li>
                  <li><a href="http://phalconphp.com/en/about">About</a></li>
                </ul>
            </div>
        </div>
    </nav>
  </header>

<div class="heading">
    <div class="container">
        <div class="row">
            <h2>Documentation</h2>
        </div>
    </div>
</div>
    <!--<div class="header-line">
      <div class="size-wrap">
        <div class="header-line-title title-white">Documentation</div>
      </div>
    </div>-->
    <div class="related">
      <ul>
        <li class="right" >
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="crypt.html" title="加密与解密（Encryption/Decryption）"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="cache.html" title="使用缓存提高性能（Improving Performance with Cache）"
             accesskey="P">上一页</a> |</li>
        <li><a href="http://phalconphp.com">Home</a> &raquo;</li>
        <li><a href="../index.html">Phalcon 2.0.0 文档</a> &raquo;</li> 
      </ul>
    </div>  

      <table width="100%" align="center" cellpadding="0" cellspacing="0">
        <tr>
      <td class="primary-box" width="25%" valign="top">
            <div>
            <div id="searchbox" style="">
                <!--<form class="search" action="http://readthedocs.org/search/project/" method="get">
                  <input type="search" name="q" size="25" placeholder="Search">
                  <input type="submit" value="Go">
                  <input type="hidden" name="selected_facets" value="project:">
                </form>-->
                <div style="width:200px;padding:10px">
                  <gcse:searchbox-only></gcse:searchbox-only>
                </div>
            </div>
            </div>
            <div style="padding:5px;padding-left:10px">
              <div id="carbonads-container">
                <div class="carbonad"><div id="azcarbon"></div>
                <script type="text/javascript">var z = document.createElement("script"); z.type = "text/javascript"; z.async = true; z.src = "http://engine.carbonads.com/z/56496/azcarbon_2_1_0_VERT"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s);</script>
                </div></div>
            </div>
            <h3><a href="../index.html">內容目录</a></h3>
            <ul>
<li><a class="reference internal" href="#">安全（Security）</a><ul>
<li><a class="reference internal" href="#password-hashing">密码散列（Password Hashing）</a></li>
<li><a class="reference internal" href="#cross-site-request-forgery-csrf-protection">防止跨站点请求伪造攻击（Cross-Site Request Forgery (CSRF) protection）</a></li>
<li><a class="reference internal" href="#setting-up-the-component">设置组件（Setting up the component）</a></li>
<li><a class="reference internal" href="#external-resources">外部资源（External Resources）</a></li>
</ul>
</li>
</ul>

            <h4>上一个主题</h4>
            <p class="topless"><a href="cache.html" title="上一章">&lt; 使用缓存提高性能（Improving Performance with Cache）</a></p>
            <h4>下一个主题</h4>
            <p class="topless"><a href="crypt.html" title="下一章">加密与解密（Encryption/Decryption） &gt;</a></p>
            <h3>本页</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/reference/security.txt" rel="nofollow">显示源代码</a></li>
            </ul>
        </td>
          <td class="second-box" valign="top">
            <div class="document">
                <div class="documentwrapper">
                  <div class="bodywrapper">
                    <div class="body" >
                      
  <div class="section" id="security">
<h1>安全（Security）<a class="headerlink" href="#security" title="永久链接至标题">¶</a></h1>
<p>该组件可以帮助开发人员在共同安全方面的一些工作，比如密码散列和跨站点请求伪造(CSRF)保护。</p>
<div class="section" id="password-hashing">
<h2>密码散列（Password Hashing）<a class="headerlink" href="#password-hashing" title="永久链接至标题">¶</a></h2>
<p>将密码以纯文本方式保存是一个糟糕的安全实践。任何可以访问数据库的人可立即访问所有用户账户，因此能够从事未经授权的活动。为解决这个问题，许多应用程序使用熟悉的
单向散列方法比如“<a class="reference external" href="http://php.net/manual/en/function.md5.php">md5</a>”和“<a class="reference external" href="http://php.net/manual/en/function.sha1.php">sha1</a>”。然而，硬件每天都在发展，变得更快，这些算法在蛮力攻击面前变得脆弱不堪。这些攻击也被称为“彩虹表（<a class="reference external" href="http://en.wikipedia.org/wiki/Rainbow_table">rainbow tables</a> ）”。</p>
<p>为了解决这个问题我们可以使用哈希算法 <a class="reference external" href="http://en.wikipedia.org/wiki/Bcrypt">bcrypt</a>。为什么 bcrypt？ 由于其“<a class="reference external" href="http://en.wikipedia.org/wiki/Bcrypt#Algorithm">Eksblowfish</a>”键设置算法，我们可以使密码加密如同我们想要的“慢”。慢的算法使计算
Hash背后的真实密码的过程非常困难甚至不可能。这可以在一个很长一段时间内免遭可能的彩虹表攻击。</p>
<p>这个组件使您能够以一个简单的方法使用该算法：</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UsersController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">registerAction</span><span class="p">()</span>
    <span class="p">{</span>

        <span class="nv">$user</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Users</span><span class="p">();</span>

        <span class="nv">$login</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">getPost</span><span class="p">(</span><span class="s1">&#39;login&#39;</span><span class="p">);</span>
        <span class="nv">$password</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">getPost</span><span class="p">(</span><span class="s1">&#39;password&#39;</span><span class="p">);</span>

        <span class="nv">$user</span><span class="o">-&gt;</span><span class="na">login</span> <span class="o">=</span> <span class="nv">$login</span><span class="p">;</span>

        <span class="c1">//Store the password hashed</span>
        <span class="nv">$user</span><span class="o">-&gt;</span><span class="na">password</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">security</span><span class="o">-&gt;</span><span class="na">hash</span><span class="p">(</span><span class="nv">$password</span><span class="p">);</span>

        <span class="nv">$user</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">();</span>
    <span class="p">}</span>

<span class="p">}</span>
</pre></div>
</div>
<p>我们保存一个用默认因子散列的密码。更高的因子可以使密码更加可靠。我们可以用如下的方法检查密码是否正确:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">SessionController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">loginAction</span><span class="p">()</span>
    <span class="p">{</span>

        <span class="nv">$login</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">getPost</span><span class="p">(</span><span class="s1">&#39;login&#39;</span><span class="p">);</span>
        <span class="nv">$password</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">getPost</span><span class="p">(</span><span class="s1">&#39;password&#39;</span><span class="p">);</span>

        <span class="nv">$user</span> <span class="o">=</span> <span class="nx">Users</span><span class="o">::</span><span class="na">findFirstByLogin</span><span class="p">(</span><span class="nv">$login</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="nv">$user</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">security</span><span class="o">-&gt;</span><span class="na">checkHash</span><span class="p">(</span><span class="nv">$password</span><span class="p">,</span> <span class="nv">$user</span><span class="o">-&gt;</span><span class="na">password</span><span class="p">))</span> <span class="p">{</span>
                <span class="c1">//The password is valid</span>
            <span class="p">}</span>
        <span class="p">}</span>

        <span class="c1">//The validation has failed</span>
    <span class="p">}</span>

<span class="p">}</span>
</pre></div>
</div>
<p>Salt使用PHP的 <a class="reference external" href="http://php.net/manual/en/function.openssl-random-pseudo-bytes.php">openssl_random_pseudo_bytes</a> 函数的伪随机字节生成的，所以需要加载扩展 <a class="reference external" href="http://php.net/manual/en/book.openssl.php">openssl</a>。</p>
</div>
<div class="section" id="cross-site-request-forgery-csrf-protection">
<h2>防止跨站点请求伪造攻击（Cross-Site Request Forgery (CSRF) protection）<a class="headerlink" href="#cross-site-request-forgery-csrf-protection" title="永久链接至标题">¶</a></h2>
<p>这是另一个常见的web站点和应用程序攻击。如用户注册或添加注释的这类表单就很容易受到这种攻击。</p>
<p>可以想到的方式防止表单值发送自外部应用程序。为了解决这个问题，我们为每个表单生成一个一次性随机令牌（<a class="reference external" href="http://en.wikipedia.org/wiki/Cryptographic_nonce">random nonce</a>），在会话中添加令牌，然后一旦表单数据提交到
程序之后，将提交的数据中的的令牌和存储在会中的令牌进行比较，来验证是否合法。</p>
<div class="highlight-html+php"><div class="highlight"><pre><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nx">Tag</span><span class="o">::</span><span class="na">form</span><span class="p">(</span><span class="s1">&#39;session/login&#39;</span><span class="p">)</span> <span class="cp">?&gt;</span>

    <span class="c">&lt;!-- login and password inputs ... --&gt;</span>

    <span class="nt">&lt;input</span> <span class="na">type=</span><span class="s">&quot;hidden&quot;</span> <span class="na">name=</span><span class="s">&quot;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">security</span><span class="o">-&gt;</span><span class="na">getTokenKey</span><span class="p">()</span> <span class="cp">?&gt;</span><span class="s">&quot;</span>
        <span class="na">value=</span><span class="s">&quot;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">security</span><span class="o">-&gt;</span><span class="na">getToken</span><span class="p">()</span> <span class="cp">?&gt;</span><span class="s">&quot;</span><span class="nt">/&gt;</span>

<span class="nt">&lt;/form&gt;</span>
</pre></div>
</div>
<p>在控制器的动作中可以检查CSRF令牌是否有效:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Mvc\Controller</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">SessionController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">loginAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">isPost</span><span class="p">())</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">security</span><span class="o">-&gt;</span><span class="na">checkToken</span><span class="p">())</span> <span class="p">{</span>
                <span class="c1">//The token is ok</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>

<span class="p">}</span>
</pre></div>
</div>
<p>记得添加一个会话适配器到依赖注入器中，否则令牌检查是行不通的:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">$di-&gt;setShared(&#39;session&#39;, function() {</span>
<span class="x">    $session = new Phalcon\Session\Adapter\Files();</span>
<span class="x">    $session-&gt;start();</span>
<span class="x">    return $session;</span>
<span class="x">});</span>
</pre></div>
</div>
<p>同时也建议为表单添加一个 <a class="reference external" href="http://www.google.com/recaptcha">captcha</a> ，以完全避免这种攻击的风险。</p>
</div>
<div class="section" id="setting-up-the-component">
<h2>设置组件（Setting up the component）<a class="headerlink" href="#setting-up-the-component" title="永久链接至标题">¶</a></h2>
<p>该组件自动在服务容器中注册为“security”,你亦可以重新注册它并为它设置参数:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Phalcon\Security</span><span class="p">;</span>

<span class="nv">$di</span><span class="o">-&gt;</span><span class="na">set</span><span class="p">(</span><span class="s1">&#39;security&#39;</span><span class="p">,</span> <span class="k">function</span><span class="p">(){</span>

    <span class="nv">$security</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Security</span><span class="p">();</span>

    <span class="c1">//Set the password hashing factor to 12 rounds</span>
    <span class="nv">$security</span><span class="o">-&gt;</span><span class="na">setWorkFactor</span><span class="p">(</span><span class="mi">12</span><span class="p">);</span>

    <span class="k">return</span> <span class="nv">$security</span><span class="p">;</span>
<span class="p">},</span> <span class="k">true</span><span class="p">);</span>
</pre></div>
</div>
</div>
<div class="section" id="external-resources">
<h2>外部资源（External Resources）<a class="headerlink" href="#external-resources" title="永久链接至标题">¶</a></h2>
<ul class="simple">
<li><a class="reference external" href="http://vokuro.phalconphp.com">Vökuró</a>, 是一个使用的安全组件避免CSRF和密码散列的示例应用程序 [<a class="reference external" href="https://github.com/phalcon/vokuro">Github</a>]</li>
</ul>
</div>
</div>


                    </div>
                  </div>
                </div>
            </div>
          </td>
        </tr>
      </table>
    <div class="related">
      <ul>
        <li class="right" >
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="crypt.html" title="加密与解密（Encryption/Decryption）"
             >下一页</a> |</li>
        <li class="right" >
          <a href="cache.html" title="使用缓存提高性能（Improving Performance with Cache）"
             >上一页</a> |</li> 
      </ul>
    </div>

      <div class="prefooter">
  <div class="container">
      <div class="row">
          <div class="col-sm-3 text-right">
              <span>Follow along:</span>
          </div>
          <div class="col-sm-6 text-center">
              <a href="https://twitter.com/phalconphp" alt="Twitter" class="btn-social btn-social-twitter"><i class="icon-twitter"></i></a>
              <a href="https://www.facebook.com/pages/Phalcon-Framework/134230726685897" alt="Facebook" class="btn-social btn-social-facebook"><i class="icon-facebook"></i></a>
              <a href="https://plus.google.com/102376109340560896457" alt="Google+" class="btn-social btn-social-googleplus"><i class="icon-googleplus"></i></a>
              <a href="https://github.com/phalcon/cphalcon" alt="Github" class="btn-social btn-social-github"><i class="icon-github"></i></a>
          </div>
          <div class="col-sm-3">
          </div>
      </div>
  </div>

</div>
<footer class="footer">
  <div class="container">
      <div class="row">
          <div class="col-xs-4 col-sm-3">
              <h4>Download</h4>
              <ul>
                  <li><a href="http://phalconphp.com/download">Installing Phalcon</a></li>
                  <li><a href="http://docs.phalconphp.com/en/latest/index.html" class="header-nav-link" target="_blank">Documentation</a></li>
                  <li><a href="http://api.phalconphp.com">API</a></li>
                  <li><a href="http://docs.phalconphp.com/en/latest/reference/tutorial.html">Tutorial</a></li>
                  <li><a href="http://docs.phalconphp.com/en/latest/reference/tutorial.html#sample-applications">Sample Applications</a></li>
              </ul>
          </div>
          <div class="col-xs-4 col-sm-3">
              <h4>Community</h4>
              <ul>
                  <li><a href="http://forum.phalconphp.com/" class="header-nav-link" target="_blank">Forum</a></li>
                  <li><a href="https://github.com/phalcon/cphalcon">GitHub</a></li>
                  <li><a href="https://github.com/phalcon/cphalcon/issues">Issue Tracker</a></li>
                  <li><a href="http://stackoverflow.com/questions/tagged/phalcon">Stack Overflow</a></li>
                  <li><a href="http://phalconphp.com/en/testimonials">Testimonials</a></li>
                  <li><a href="http://builtwith.phalconphp.com/">Built with Phalcon</a></li>
                  <li><a href="http://store.phalconphp.com/">Store</a></li>
              </ul>
          </div>
          <div class="col-xs-4 col-sm-2">
              <h4>About</h4>
              <ul>
                  <li><a class="link-black" href="http://blog.phalconphp.com/">Blog</a></li>
                  <li><a href="http://phalconphp.com/en/about">About</a></li>
                  <li><a href="http://phalconphp.com/en/team">Team</a></li>
                  <li><a href="http://phalconphp.com/en/roadmap">Roadmap</a></li>
                  <li><a href="http://phalconphp.com/en/donate">Donate</a></li>
                  <li><a href="http://phalconphp.com/en/consulting">Consulting</a></li>
                  <li><a href="http://phalconphp.com/en/hosting">Hosting</a></li>
              </ul>
          </div>
          <div id="license-spaccer" class="visible-xs"></div>
          <div id="license-wrapper" class="col-xs-12 col-sm-4">
              <p class="license">

                  Found a typo or an error? Want to improve this document? The documentation sources are available on <a href="http://github.com/phalcon/docs">Github</a><br>
                  Need support or have questions? Check our <a href="http://forum.phalconphp.com">Forum</a><br>
                  <br>

                  Phalcon Framework is released under the <a href="https://github.com/phalcon/cphalcon/blob/master/docs/LICENSE.md">new BSD license</a>.<br>
                  Except where otherwise noted, content on this site is licensed under the
                    <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License.</a>

                <div class="design">
                  <span>Designed by:</span>

                  <a href="http://www.fog-city.net/" class="fogcity" target="_blank" title="Fog City Software"><span>Fog City Software</span></a>
              </div>
          </div>
      </div>
  </div>
</footer>

    </div>
    <script type="text/javascript">
    $(window).on("load", function(){
      var cx = '009733439235723428699:lh9ltjgvdz8';
      var gcse = document.createElement('script');
      gcse.type = 'text/javascript';
      gcse.async = true;
      gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx;
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(gcse, s);
    });
    </script>

  </body>
</html>